<!--
 * @Description: 添加/展示/编辑消息模板的弹窗
 * @Version: 1.0
 * @Autor: chen_yt
 * @Date: 2020-11-02 17:15:31
 * @LastEditors: wei_jt@ecidi.com
 * @LastEditTime: 2022-07-13 13:47:22
-->

<template>
  <div class="dialog-for-column">
    <fks-dialog
      v-if="Visible"
      :class="operateType == 'show' ? 'view' : ''"
      :visible.sync="Visible"
      :append-to-body="true"
      width="960px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      @close="close"
    >
      <template slot="title">
        <i :class="iconClass" />
        <span>{{ DialogTitle }}</span>
      </template>

      <div class="column-edit">
        <fks-form
          ref="Form"
          v-loading="loading"
          :model="Form"
          labfks-position="left"
          labfks-width="84px"
          :disabled="operateType == 'show'"
          :rules="rules"
        >
          <fks-form-item
            :span="12"
            :label="LANG.TEMPLATE_NAME"
            prop="templateName"
          >
            <fks-input
              v-model="Form.templateName"
              maxlength="50"
              show-word-limit
            />
          </fks-form-item>
          <fks-form-item
            :span="12"
            :label="LANG.MSG_SEND_TYPE"
            prop="supportedMsgSendTypes"
          >
            <fks-select
              v-model="Form.supportedMsgSendTypes"
              style="width: 100%"
              disabled
              @change="msgSendTypeChange()"
            >
              <fks-option
                v-for="item in msgSendTypeList"
                :key="item.code"
                :value="item.code"
                :label="item[$lang]"
              />
            </fks-select>
          </fks-form-item>
          <fks-form-item
            v-if="msgSendType != 0"
            :span="24"
            :label="LANG.SERVER"
            required
            prop="serverId"
          >
            <fks-select v-model="Form.serverId" style="width: 100%">
              <fks-option
                v-for="item in serverList"
                :key="item.id"
                :value="item.id"
                :label="item.serverName"
              />
            </fks-select>
          </fks-form-item>
          <fks-form-item
            v-show="!loading"
            :span="24"
            :label="LANG.PARAMS_CONTENT"
          >
            <Editor
              v-if="
                operateType != 'show' &&
                (msgSendType == '2' || msgSendType == '0')
              "
              ref="Editor"
              v-model="Form.template"
              class="editor"
              :placeholder="LANG.DEMO_TEMPLATE"
            />
            <fks-input
              v-else
              v-model="Form.template"
              type="textarea"
              :rows="10"
              :placeholder="LANG.DEMO_TEMPLATE"
            />
          </fks-form-item>

          <fks-form-item :span="24" :label="LANG.SEND_PARAMS">
            <fks-table
              :data="Form.defaultParams"
              style="width: 100%"
              size="samll"
            >
              <fks-table-column
                label="#"
                type="index"
                align="center"
                :resizable="false"
              />
              <fks-table-column
                prop="name"
                :label="LANG.PARAM_NAME"
                align="center"
              >
                <template slot-scope="scope">
                  <div>{{ scope.row.name }}</div>
                </template>
              </fks-table-column>
              <fks-table-column
                prop="value"
                :label="LANG.PARAM_DEFAULT_VALUE"
                align="center"
              >
                <div slot-scope="scope">
                  <div v-if="!scope.row.type">
                    {{ scope.row.value }}
                  </div>
                  <div v-if="scope.row.type == 'edit'">
                    <fks-input
                      v-model="scope.row.value"
                      maxlength="50"
                      @keyup.enter.native="rowSave(scope.row)"
                    />
                  </div>
                </div>
              </fks-table-column>

              <fks-table-column
                :label="LANG.OPERATION"
                width="140"
                align="center"
              >
                <span slot-scope="scope">
                  <fks-button
                    v-if="!scope.row.type"
                    class="table-column-opt-button"
                    type="text"
                    @click="editHandler(scope.row)"
                    >{{ LANG.EDIT }}</fks-button
                  >
                  <fks-button
                    v-if="scope.row.type == 'edit'"
                    class="table-column-opt-button"
                    type="text"
                    @click="defaultParamsCancel(scope)"
                    >{{ LANG.CANCEL }}</fks-button
                  >
                  <fks-button
                    v-if="scope.row.type == 'edit'"
                    class="table-column-opt-button"
                    type="text"
                    @click="rowSave(scope.row)"
                    >{{ LANG.SAVE }}</fks-button
                  >
                  <!-- <fks-button
                        class="table-column-opt-button"
                        @click="cancelAdd(scope)"
                        type="text"
                        style="color: #ff4d4f"
                        >{{ LANG.DELETE }}</fks-button
                  >-->
                </span>
              </fks-table-column>
            </fks-table>
          </fks-form-item>

          <!-- 模板可变字段的参数 -->

          <fks-form-item :span="24" :label="LANG.TEMPLATE_PARAMS" prop="meta">
            <div
              v-show="operateType != 'show'"
              style="padding-bottom: 16px; text-align: right"
            >
              <fks-button
                icon="fks-icon-plus"
                size="small"
                @click="addTemplateParam"
              >
                {{ LANG.ADD }}
              </fks-button>
            </div>
            <fks-table :data="Form.paramsList" style="width: 100%" size="samll">
              <fks-table-column
                label="#"
                type="index"
                align="center"
                :resizable="false"
              />
              <fks-table-column
                prop="name"
                :label="LANG.PARAM_NAME"
                align="center"
              >
                <div slot-scope="scope">
                  <div v-if="!scope.row.type">
                    {{ scope.row.name }}
                  </div>
                  <div v-if="scope.row.type == 'edit'">
                    <fks-input
                      v-model="scope.row.name"
                      maxlength="50"
                      @keyup.enter.native="rowSave(scope.row)"
                    />
                  </div>
                </div>
              </fks-table-column>
              <fks-table-column
                prop="value"
                :label="LANG.PARAM_DEFAULT_VALUE"
                align="center"
              >
                <div slot-scope="scope">
                  <div v-if="!scope.row.type">
                    {{ scope.row.value }}
                  </div>
                  <div v-if="scope.row.type == 'edit'">
                    <fks-input
                      v-model="scope.row.value"
                      maxlength="50"
                      @keyup.enter.native="rowSave(scope.row)"
                    />
                  </div>
                </div>
              </fks-table-column>

              <fks-table-column
                :label="LANG.OPERATION"
                align="center"
                width="140"
              >
                <div slot-scope="scope">
                  <fks-button
                    v-if="!scope.row.type"
                    class="table-column-opt-button"
                    type="text"
                    @click="editHandler(scope.row)"
                  >
                    {{ LANG.EDIT }}
                  </fks-button>
                  <fks-button
                    v-if="scope.row.type == 'edit'"
                    class="table-column-opt-button"
                    type="text"
                    @click="paramsListCancel(scope)"
                  >
                    {{ LANG.CANCEL }}
                  </fks-button>
                  <fks-button
                    v-if="scope.row.type == 'edit'"
                    class="table-column-opt-button"
                    type="text"
                    @click="rowSave(scope.row)"
                  >
                    {{ LANG.SAVE }}
                  </fks-button>
                  <fks-button
                    class="table-column-opt-button"
                    type="text"
                    style="color: #ff4d4f"
                    @click="cancelAdd(scope, Form.paramsList)"
                  >
                    {{ LANG.DELETE }}
                  </fks-button>
                </div>
              </fks-table-column>
            </fks-table>
          </fks-form-item>
        </fks-form>
      </div>
      <!-- 提交按钮 -->
      <template slot="footer">
        <fks-button
          v-show="operateType != 'show' && !loading"
          type="primary"
          icon="fks-icon-check"
          @click="submit"
        >
          {{ LANG.SAVE }}
        </fks-button>
      </template>
    </fks-dialog>
  </div>
</template>

<script>
import Editor from "@/components/Editor";
import { addTemplate, getDefaultParams, getServerConfig } from "../../api";
import { ENUM } from "@/store/State/stateTypes";
import { getMsgTemplateById } from "../../api";

export default {
  name: "MsgAndEmail",
  components: {
    Editor,
  },
  props: {
    visible: {
      type: Boolean,
    },
    operateType: {
      type: String,
      default: "new",
    },
    templateId: {
      type: String,
    },
    msgSendType: {
      type: String,
    },
  },
  data() {
    return {
      Visible: false,
      loading: true,
      Form: {},
      defaultParams: [],
      paramsList: [],
      paramsDataList: [],
      serverList: [],
      rules: {
        templateName: [{ required: true }],
      },
    };
  },
  computed: {
    DialogTitle() {
      if (this.operateType == "new") return this.LANG.ADD;
      if (this.operateType == "edit") return this.LANG.EDIT;
      return this.LANG.VIEW;
    },
    msgSendTypeList() {
      return this.$store.state[ENUM].msgSendType || [];
    },
    msgType() {
      return this.$store.state[ENUM].msgType || [];
    },
    iconClass() {
      if (this.operateType == "new") return "fks-icon-plus";
      if (this.operateType == "edit") return "fks-icon-edit";
      return "fks-icon-view";
    },
  },

  watch: {
    visible(val) {
      this.Visible = val;
      if (val) {
        this.resetData();
        this.initData();
      }
    },
  },
  mounted() {},
  methods: {
    addTemplateParam() {
      this.Form.paramsList.push({
        name: "",
        value: "",
        type: "edit",
      });
    },

    rowSave(data) {
      //判断是否存在同名
      if (data.name == "") {
        this.$message({
          type: "error",
          message: this.LANG.ERROR_PARAM_NAME_NULL,
        });
        return;
      }
      let allParams = [...this.Form.defaultParams, ...this.Form.paramsList];
      let same = 0;
      for (let i = 0; i < allParams.length; i++) {
        if (allParams[i].name == data.name) {
          same++;
          if (same > 1) {
            this.$message({
              type: "error",
              message: this.LANG.ERROR_PARAM_NAME_DUPLICATE,
            });
            return;
          }
        }
      }
      data.type = "";
    },
    paramsListCancel(scope) {
      let data = {};
      data = this.paramsDataList.find((item) => {
        return item.name == scope.row.name;
      });
      this.$set(
        this.Form.paramsList[scope.$index],
        "value",
        data?.value ? data.value : ""
      );
      this.$set(this.Form.paramsList[scope.$index], "type", "");
    },
    defaultParamsCancel(scope) {
      let data = {};
      data = this.paramsDataList.find((item) => {
        return item.name == scope.row.name;
      });
      this.$set(
        this.Form.defaultParams[scope.$index],
        "value",
        data.value ? data.value : ""
      );
      this.$set(this.Form.defaultParams[scope.$index], "type", "");
    },
    editHandler(data) {
      if (
        !this.paramsDataList.find((item) => {
          return item.name == data.name;
        })
      ) {
        this.paramsDataList.push(JSON.parse(JSON.stringify(data)));
      } else {
        this.paramsDataList.forEach((item) => {
          if (item.name == data.name && data.value) {
            item.value = data.value;
          }
        });
      }
      data.type = "edit";
    },
    cancelAdd(data, list) {
      list.splice(data.$index, 1);
      let index = this.paramsDataList.findIndex((item) => {
        return item.name == data.row.name;
      });
      this.paramsDataList.splice(index, 1);
    },

    msgSendTypeChange() {
      let index = this.Form.supportedMsgSendTypes;
      this.getDefaultParams(index);
    },

    getDefaultParams(index) {
      return getDefaultParams(index)
        .then((res) => {
          if (res.status && res.data) {
            let paramsList = res.data.split(",");
            this.defaultParams = paramsList.filter((item) => {
              return item != "serverId";
            });
          }
        })
        .catch(() => {});
    },
    getServerList() {
      return getServerConfig()
        .then((res) => {
          if (res.status) {
            let serverData = [];
            switch (this.msgSendType) {
              case "2": {
                serverData = res.data.mailServerConfig ?? [];
                break;
              }
              case "3": {
                serverData = res.data.jpushServerConfig ?? [];
                break;
              }
              case "5": {
                serverData = res.data.qywxServerConfig ?? [];
                break;
              }
              case "4": {
                serverData = res.data.dingTalkServerConfig ?? [];
                break;
              }
              case "7": {
                serverData = res.data.larkServerConfig ?? [];
                break;
              }
            }
            this.serverList = serverData.filter((item) => {
              return item.state;
            });
          }
        })
        .catch(() => {});
    },
    /**
     * @description: 将form处理为与接口对应的形式
     * @param {Object} form 表单的form
     * @return {Object} newForm 用于提交的form
     */
    dealForSubmit(form) {
      let newForm = JSON.parse(JSON.stringify(form));
      delete newForm.serverId;
      newForm.supportedMsgTypes = newForm.msgType.join();
      let allParams = [
        ...form.defaultParams,
        ...form.paramsList,
        { name: "serverId", type: "", value: form.serverId },
      ];
      let arr = [];
      let obj = {};
      allParams.forEach((item) => {
        arr.push(item.name);
        obj[item.name] = item.value;
      });
      newForm.templateParamList = arr.join();
      newForm.templateParamDefaultValue = JSON.stringify(obj);
      return newForm;
    },

    submit() {
      this.$refs["Form"].validate((valid) => {
        if (valid) {
          this.submitCheck();
        }
        if (!valid) {
          this.$message({
            type: "error",
            message: this.LANG.ERROR_UNDO,
          });
          return;
        }
      });
    },

    submitCheck() {
      let params = [];
      params = [...this.Form.template.matchAll(/\$\{(.*?)\}/gi)];
      if (params.length > 0) {
        params.forEach((item) => {
          if (
            !this.Form.paramsList.find((param) => {
              return item[1] == param.name;
            })
          ) {
            this.Form.paramsList.push({
              name: item[1],
              value: "",
              type: "",
            });
          }
        });
      }
      let allParams = [...this.Form.defaultParams, ...this.Form.paramsList];
      for (let i = 0; i < allParams.length; i++) {
        if (allParams[i].type == "edit") {
          this.$message({
            type: "error",
            message: this.LANG.ERROR_PARAM_NOT_SAVE,
          });
          return;
        }
      }
      // let flag = false
      // this.Form.defaultParams.forEach((item) => {
      //   if (!item.value) {
      //     flag = true
      //   }
      // })
      // if (flag) {
      //   this.$message({
      //     type: 'error',
      //     message: this.LANG.ERROR_PARAMS_REQUIRED
      //   })
      //   return
      // }
      this.submitForm();
    },

    submitForm: async function () {
      let submitForm = this.dealForSubmit(this.Form);
      addTemplate(submitForm, this.operateType)
        .then((res) => {
          if (res.status) {
            this.$message({
              type: "success",
              message:
                this.operateType == "new"
                  ? this.LANG.ADD_SUCCESS
                  : this.LANG.EDIT_SUCCESS,
            });
            this.$emit("submit");
          }
        })
        .catch(() => {});
    },

    resetData() {
      this.Form = {
        msgType: [],
        paramsList: [],
        defaultParams: [],
        supportedMsgSendTypes: this.msgSendType,
        template: "",
      };
      this.defaultParams = [];
      this.paramsList = [];
    },
    cancel() {
      this.close();
    },
    close() {
      this.$emit("close");
      this.resetData();
    },

    pushIntoTable(name, valueObject, table) {
      let temp = {
        name: name,
        value: valueObject[name],
        type: "",
      };
      table.push(temp);
    },

    /**
     * @description: 初始化Dialog
     *
     */
    initData: async function () {
      this.loading = true;

      await this.getDefaultParams(this.msgSendType);
      if (this.msgSendType != 0) {
        await this.getServerList();
      }
      if (this.operateType == "new") {
        for (let i = 0; i < this.defaultParams.length; i++) {
          this.pushIntoTable(
            this.defaultParams[i],
            [],
            this.Form.defaultParams
          );
        }
        this.loading = false;
      }

      if (this.operateType == "edit" || this.operateType == "show") {
        getMsgTemplateById(this.templateId)
          .then((res) => {
            if (res.status) {
              let templateInfo = res.data;
              //把模板服务器id从默认参数中赋值给form中的serverId字段
              if (this.msgSendType != 0) {
                let templateParamDefaultValue = JSON.parse(
                  res.data.templateParamDefaultValue
                );
                this.Form.serverId = templateParamDefaultValue.serverId;
              }
              //勾选的消息类型
              if (templateInfo.supportedMsgTypes) {
                this.Form.msgType = templateInfo.supportedMsgTypes.split(",");
              }

              //模板参数/发送参数置入
              if (templateInfo.templateParamList) {
                //此处去重
                //消息发送方式带来的必选字段
                //不会出现在消息参数中

                let arr = templateInfo.templateParamList.split(",");

                for (let i = 0; i < arr.length; i++) {
                  let item = arr[i];
                  if (this.defaultParams.indexOf(item) < 0)
                    //模板参数
                    this.paramsList.push(item);
                }
              }

              let paramsValueList = JSON.parse(
                templateInfo.templateParamDefaultValue
              );

              for (let i = 0; i < this.paramsList.length; i++) {
                this.pushIntoTable(
                  this.paramsList[i],
                  paramsValueList,
                  this.Form.paramsList
                );
              }

              for (let i = 0; i < this.defaultParams.length; i++) {
                this.pushIntoTable(
                  this.defaultParams[i],
                  paramsValueList,
                  this.Form.defaultParams
                );
              }
              this.Form = { ...this.Form, ...templateInfo };
            }
            this.loading = false;
          })
          .catch(() => {
            this.loading = false;
          });
      }
    },
  },
};
</script>

<style scoped lang="scss">
::v-deep .fks-dialog__body {
  padding-bottom: 0;
}
.editor {
  border-radius: 4px;
  ::v-deep .w-e-text-container {
    border-radius: 4px;
  }
  ::v-deep .w-e-bar {
    border-radius: 4px;
  }
}
</style>
